console.log('进入工单系统');


// 监听点击完成工单按钮
document.addEventListener('click', function(e) {  // async
  const buttonMatch = e.target.closest('.el-button.el-button--info.btn_custom');
  const stepItemMatch = e.target.closest('.step_item');

  if ((buttonMatch && buttonMatch.textContent.includes('完成工单')) ||
      (stepItemMatch && stepItemMatch.querySelector('.step_item_text')?.textContent.includes('已完成'))) {
    
    console.log("已点击完成工单");
    process();
  }

  // if (e.target.closest('.el-button.el-button--primary') && 
  //     e.target.textContent.includes('确定')) {
  //   // await delay(1000);
  //   console.log('点了确认');
  //   if (!document.querySelector('.plugin-state')) {
  //     const span_state = `
  //       <span class="" style="padding: 0 16px;">
  //         <span class="plugin-state">Waiting...</span>
  //         <button aria-disabled="false" type="button" class="">
  //             <span class="plugin-cancel" style="padding: 6px; color: #4a7dff">取消</span>
  //         </button>
  //       </span>`;
  //     const span_state_element = new DOMParser().parseFromString(span_state, 'text/html');
  //     document.querySelector('.dialog-footer').prepend(span_state_element);
  //   }
  //   document.querySelector('.plugin-state').style.display = 'block';
  // }
});

// 监听双击完成工单按钮
document.addEventListener('dblclick', function(e) {  // async
  const buttonMatch = e.target.closest('.el-button.el-button--info.btn_custom');
  const stepItemMatch = e.target.closest('.step_item');

  if ((buttonMatch && buttonMatch.textContent.includes('完成工单')) ||
      (stepItemMatch && stepItemMatch.querySelector('.step_item_text')?.textContent.includes('已完成'))) {
    
    console.log("已双击完成工单");

    const textarea = document.querySelector('.custom_input');
    textarea.value = '这个工单先关闭了，您有其他问题可以再提新的工单，祝您生活愉快！';
    
    process();
  }
});


// 接收background.js返回的总结结果并填写表单
chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
  if (request.action === 'fill') {
    console.log('收到后台结果：', request);

    const category_1 = parseInt(request.category_id.slice(0, 1)) - 1;
    const category_2 = parseInt(request.category_id.slice(2, 3)) - 1;

    const lable_div = document.querySelectorAll('.el-overlay:not([style*="display: none"])')[0];

    // 分类
    const category_label_1 = Array.from(
      lable_div.querySelectorAll('label.el-form-item__label')
    ).find(label => 
      label.textContent.trim() === '分类'
    );
    const category_input_1 = lable_div.querySelector('#' + category_label_1.getAttribute('for'));
    const category_ul_1 = document.getElementById(category_input_1.getAttribute('aria-controls'));
    category_ul_1.children[category_1].click();
    
    await delay(500);

    // 子分类
    const category_label_2 = Array.from(
      lable_div.querySelectorAll('label.el-form-item__label')
    ).find(label => 
      label.textContent.trim() === '子分类'
    );
    const category_input_2 = lable_div.querySelector('#' + category_label_2.getAttribute('for'));
    const category_ul_2 = document.getElementById(category_input_2.getAttribute('aria-controls'));
    category_ul_2.children[category_2].click();

    // 补充描述
    const description_label = Array.from(
      lable_div.querySelectorAll('label.el-form-item__label')
    ).find(label => 
      label.textContent.trim() === '补充描述'
    );
    const description_input = lable_div.querySelector('#' + description_label.getAttribute('for'));
    
    if (description_input) {
      description_input.value = request.description;
    }

    // document.querySelector('.plugin-state').textContent = '已完成';
    // document.querySelector('.plugin-state').style.display = 'none';
  } else if (request.action === 'error') {
    console.error('收到后台错误信息：', request.error);
    console.log('返回的结果是：', request.result);
  }  return true;
});


function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}


function process() {
  // if (document.querySelector('.plugin-state')) {
  //   document.querySelector('.plugin-state').textContent = '正在获取对话内容';
  // }

  // 提取所有聊天记录
  const chatItems = document.querySelectorAll('.chat_item');
  let conversation = [];

  conversation.push({
    role: '客户',
    content: document.querySelector('.question_describe_text')?.textContent.trim(),
  })
  
  chatItems.forEach(item => {
    const isClient = item.classList.contains('client');
    const isEngineer = item.classList.contains('me');
    const content = item.querySelector('.content pre')?.textContent.trim();
    
    if (content) {
      conversation.push({
        role: isClient ? '客户' : '工程师',
        content: content,
      });
    }
  });

  console.log('对话内容：', conversation);

  // if (document.querySelector('.plugin-state')) {
  //   document.querySelector('.plugin-state').textContent = '正在生成分类和描述';
  // }
  
  // 发送给background.js处理
  chrome.runtime.sendMessage(
    {action: 'summarize', data: conversation}, 
  );
}





// 测试：
// window.postMessage(10)
window.addEventListener("message", (event) => {
  if (event.data === 10) {
    process();
  }
});